package com.android.webttest.service;

import android.Manifest;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.util.Log;

import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.lifecycle.ViewModelProvider;

import com.android.webttest.R;
import com.android.webttest.View.MainActivity;
import com.android.webttest.ViewModel.GoodViewModel;
import com.android.webttest.utils.RoomDBTools;

import org.jetbrains.annotations.Nullable;

import java.util.Arrays;
import java.util.List;

public class GoodSyncService extends Service {

    private static final String TAG = "GoodSyncService";
    private HandlerThread handlerThread;
    private Handler backgroundHandler;

    private GoodViewModel goodViewModel;
    private Runnable syncRunnable;
    private static final long SYNC_INTERVAL = 2 * 60 * 1000; // 2分钟同步一次

    @Override
    public void onCreate() {
        super.onCreate();
        handlerThread = new HandlerThread("GoodSyncThread");
        handlerThread.start();
        backgroundHandler = new Handler(handlerThread.getLooper());

        // 初始化 ViewModel（需传入 Application Context）
        goodViewModel = new ViewModelProvider.AndroidViewModelFactory(getApplication())
                .create(GoodViewModel.class);

        // 定义同步任务
        syncRunnable = new Runnable() {
            @Override
            public void run() {
                syncGoodsData();
                backgroundHandler.postDelayed(this, SYNC_INTERVAL);
            }
        };
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        backgroundHandler.post(syncRunnable);
        return START_STICKY;
    }

    private void syncGoodsData() {
        Log.d(TAG, "开始同步商品数据...");

        //获取Category--更新数据
        goodViewModel.getGoodCategoryList();
        // 创建通知
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "promotion_channel_id")
                .setSmallIcon(R.drawable.ic_promotion)
                .setContentTitle("促销活动提醒")
                .setContentText("我们的应用有新的促销活动，快来查看吧！")
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setAutoCancel(true);

        // 显示通知
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) {
                notificationManager.notify(1, builder.build());
            }
        } else {
            notificationManager.notify(1, builder.build());
        }
        //搜索历史表修改
        RoomDBTools.updateEveryDaySearchHistory();


        //发送数据--todo

        Log.d(TAG, "商品数据同步完成");
    }


    @Override
    public void onDestroy() {
        backgroundHandler.removeCallbacks(syncRunnable);
        handlerThread.quitSafely();
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
